<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>编辑验证消息</title>
    <link rel="stylesheet" href="../assets/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../assets/style/admin.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <script src="../assets/layui/layui.js"></script>
    <script src="../assets/js/common.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../common/header.js"></script>
    <!-- 内容主体区域 -->
    <div id="LAY_app_body">
        <div class="layui-fluid">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-header">
                            <a href="../customer_source/add.html" class="layui-btn layui-btn-sm layui-btn-normal">1、导入数据</a>
                            <i class="layui-icon layui-icon-right" style="font-size: 20px;"></i>
                            <a href="../../code/message/editGroupEnhance.html" class="layui-btn layui-btn-sm">2、编辑验证消息</a>
                            <i class="layui-icon layui-icon-right" style="font-size: 20px;"></i>
                            <a href="../add_friend_plan/add.html" class="layui-btn layui-btn-sm layui-btn-normal">3、创建加人计划</a>
                        </div>
                        <div class="layui-card-body">
                            <form class="layui-form" action="">
                                <input type="hidden" name="id" value="">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="name" lay-verify="name" autocomplete="off" placeholder="请输入组名称" class="layui-input" value="">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-inline">
                                        <input type="radio" name="status" value="1" title="启用" checked>
                                        <input type="radio" name="status" value="0" title="禁用" >
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <hr class="layui-bg-gray">
                                </div>
                                <div id="messageBlock">
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-line">
                                        <label class="layui-form-label"></label>
                                        <label class="layui-word-aux">变量来源于导入的数据，如有增加请联系负责人</label>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-line">
                                        <label class="layui-form-label"></label>
                                        <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="addMessage();" id="addMessageBtn">增加验证消息</button>
                                        <label id="messageState"></label>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <hr class="layui-bg-gray">
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <button type="button" class="layui-btn layui-btn-warm" onclick="preview();">预览</button>
                                        <a class="layui-btn" lay-submit lay-filter="formSubmit">保存</a>
                                        <a class="layui-btn layui-btn-primary" href="groupIndex.html">取消</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var mapLanguage = new Array();
        mapLanguage['surname'] = '姓';
        mapLanguage['name'] = '姓名';
        mapLanguage['shop'] = '店铺';
        mapLanguage['order'] = '订单号';
        mapLanguage['item'] = '产品名';
        mapLanguage['province'] = '收货人省份';
        mapLanguage['city'] = '收货人城市';
        mapLanguage['area'] = '收货人区县';
        mapLanguage['logistics'] = '快递公司';
        mapLanguage['track'] = '快递单号';
        mapLanguage['wx_nickname'] = '微信昵称';
        mapLanguage['my_nickname'] = '小号微信昵称';
        mapLanguage['weixin'] = '电话号';

        var getMessages;
        var displayMessage;
        var getMessageHtml;
        var messageCount = 0;
        var segmentCount = 0;
        var removeSegmentBtn;
        var removeSegment;
        var addSegmentBtn;
        var addSegment;
        var addMessage;
        var removeMessageBtn;
        var removeMessage;
        var displayRemoveMessageBtn;
        var hideRemoveMessageBtn;
        var messageLimit = 20;
        var messageNum = 0;
        var preview;
        var previewData;
        var getCustomerSources;

        layui.use(['element', 'form', 'laytpl'], function(){
            var $ = layui.$
                ,element = layui.element
                ,form = layui.form
                ,laytpl = layui.laytpl;

            getMessages = function(groupId) {
                var msgIndex = layer.msg('加载中...', {
                    shadeClose: false
                    ,icon: 16
                    ,shade: 0.01
                });
                $.ajax({
                    type: "GET",
                    url: "/message/list_data/"+groupId+"?page=1&limit=20&status=1",
                    success:function(response){
                        var dataObj=$.parseJSON(response);
                        if (dataObj.code === 0) {
                            var messages = dataObj.data;
                            for (var i=0; i<messages.length; i++) {
                                var item = messages[i];
                                if (item.json) {
                                    var messageId = item.id;
                                    var message = $.parseJSON(item.json);
                                    displayMessage(messageId, message);
                                }
                            }
                        } else {
                            layer.msg(dataObj.msg, {icon: 5});
                        }
                        layer.close(msgIndex);
                    },
                    error: function (request, status, error) {
                        layer.msg('哦噢，网络开小差了', {icon: 5});
                    }
                });
            };

            displayMessage = function (messageId, message) {
                if (messageNum >= messageLimit) {
                    layer.alert('当前组最多只能添加'+messageLimit+'条验证消息');
                    return false;
                }
                manageMessageNum('add');
                messageCount++;
                var thisMessageCount = messageCount;
                var messageHtml = '<div id="message'+thisMessageCount+'" class="layui-form-item message-line">';
                messageHtml += '<input type="hidden" name="messageId" value="'+messageId+'">';
                messageHtml += '<div class="layui-inline"><label class="layui-form-label">验证消息'+thisMessageCount+':</label></div>';
                messageHtml += '<div class="layui-inline">';
                for (var i=0; i<message.length; i++) {
                    var item = message[i];
                    messageHtml += getMessageHtml(item);
                }
                messageHtml += '<div id="btnGroup'+thisMessageCount+'" class="layui-btn-group">';
                messageHtml += addSegmentBtn(thisMessageCount, 'select');
                messageHtml += addSegmentBtn(thisMessageCount, 'input');
                messageHtml += removeMessageBtn(thisMessageCount);
                messageHtml += '</div>';
                messageHtml += '</div>';
                messageHtml += '<div class="layui-form-item"><hr class="layui-bg-gray"></div>';
                messageHtml += '</div>';
                $('#messageBlock').append(messageHtml);
                form.render();
            };

            getMessageHtml = function (segment) {
                segmentCount++;
                var thisSegmentCount = segmentCount;
                var html = '';
                var segmentHtml = '';
                var width = 100;
                var match = segment.match(/{(\S*)}/);
                if (match && match[1]) {
                    var current = match[1];
                    segmentHtml = selectSegment(thisSegmentCount, current);
                } else {
                    segmentHtml = inputSegment(thisSegmentCount, segment);
                    width = 150;
                }
                html += '<div class="layui-input-inline segment-item" style="width: '+width+'px;" id="segment'+thisSegmentCount+'" onmouseover="displayRemoveMessageBtn('+thisSegmentCount+');" onmouseout="hideRemoveMessageBtn('+thisSegmentCount+');">';
                html += removeSegmentBtn(thisSegmentCount);
                html += segmentHtml;
                html += '</div>';
                return html;
            };

            displayRemoveMessageBtn = function (thisSegmentCount) {
                $('#removeSegmentBtn'+thisSegmentCount).css('display', 'block');
            };

            hideRemoveMessageBtn = function (thisSegmentCount) {
                $('#removeSegmentBtn'+thisSegmentCount).css('display', 'none');
            };

            var selectSegment = function (thisSegmentCount, current) {
                var html = '<select id="segmentPost'+thisSegmentCount+'" name="segmentPost'+thisSegmentCount+'">';
                for (var index in mapLanguage) {
                    var item = mapLanguage[index];
                    html += '<option value="{'+index+'}" '+(current == index ? 'selected' : '')+'>'+item+'</option>';
                }
                html += '</select>';
                return html;
            };

            var inputSegment = function (thisSegmentCount, segment) {
                return '<input type="text" id="segmentPost'+thisSegmentCount+'" name="segmentPost'+thisSegmentCount+'" placeholder="请输入文字" required lay-verify="required" value="'+segment+'" autocomplete="off" class="layui-input">';
            };

            removeSegmentBtn = function (thisSegmentCount) {
                return '<i id="removeSegmentBtn'+thisSegmentCount+'" class="layui-icon layui-icon-delete" style="z-index: 1;position: absolute;float: left;cursor: pointer;font-size: 20px; color: #ff1717;display: none;" onclick="removeSegment(this, '+thisSegmentCount+');"></i>';
            };

            removeSegment = function (btn, thisSegmentCount) {
                layer.confirm('确认删除此验证消息模块？', function(index){
                    $('#segment'+thisSegmentCount).remove();
                    btn.remove();
                    layer.close(index);
                });
            };

            addSegmentBtn = function (thisMessageCount, type) {
                var btnText = '';
                var btnType = '';
                if (type == 'select') {
                    btnText = '变量';
                    btnType = 1;
                } else if (type == 'input') {
                    btnText = '自定义内容';
                    btnType = 2;
                }
                return '<button type="button" class="layui-btn layui-btn-sm" onclick="addSegment('+thisMessageCount+', this, '+btnType+');"><i class="layui-icon layui-icon-add-1"></i>'+btnText+'</button>';
            };

            addSegment = function (thisMessageCount, btn, btnType) {
                var html = '';
                segmentCount++;
                var thisSegmentCount = segmentCount;
                var width = 100;
                if (btnType == 2) {
                    width = 150;
                }
                html += '<div class="layui-input-inline  segment-item" style="width: '+width+'px;" id="segment'+thisSegmentCount+'" onmouseover="displayRemoveMessageBtn('+thisSegmentCount+');" onmouseout="hideRemoveMessageBtn('+thisSegmentCount+');">';
                html += removeSegmentBtn(thisSegmentCount);
                if (btnType == 1) {
                    html += selectSegment(thisSegmentCount, '');
                } else if (btnType == 2) {
                    html += inputSegment(thisSegmentCount, '');
                }
                html += '</div>';
                $('#btnGroup'+thisMessageCount).before(html);
                form.render();
                $('#segmentPost'+thisSegmentCount).focus();
            };

            removeMessageBtn = function (thisMessageCount) {
                return '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm" title="删除验证消息" onclick="removeMessage('+thisMessageCount+');"><i class="layui-icon layui-icon-close"></i></button>';
            };

            removeMessage = function (thisMessageCount) {
                layer.confirm('确认删除此验证消息？', function(index){
                    $('#message'+thisMessageCount).remove();
                    layer.close(index);
                    manageMessageNum('remove');
                });
            };

            addMessage = function () {
                displayMessage(0, '');
            };

            var manageMessageNum = function (type) {
                if (type == 'add') {
                    messageNum++;
                    if (messageNum >= messageLimit) {
                        $('#addMessageBtn').addClass('layui-btn-disabled');
                    }
                } else if (type == 'remove') {
                    messageNum--;
                    if (messageNum < messageLimit) {
                        $('#addMessageBtn').removeClass('layui-btn-disabled');
                    }
                }
                var messageState = '本组已添加 <span style="color: #00CC00">'+messageNum+'</span> 条验证消息，还可以添加 <span style="color: #0000FF">'+(messageLimit-messageNum)+'</span> 条。<span style="color: #FF0000">每条验证消息最多50个中文，100个字符。</span>';
                $('#messageState').html(messageState);
            };

            var buildMessageJson = function () {
                var messageArray = new Array();
                var messageLines = $.find('.message-line');
                messageLines.map(function (index, line) {
                    var messageLineArray = new Array();
                    var segmentArray = new Array();
                    var segments = $(index).find('.segment-item');
                    var messageId = $(index).find('input[name="messageId"]').val();
                    segments.map(function (index2, item) {
                        var segmentValue;
                        var select = $(item).find('select');
                        if (select) {
                            if (select.val() != '') {
                                segmentValue = select.val();
                            }
                        }
                        if (segmentValue === undefined) {
                            var input = $(this).find('input');
                            if (input) {
                                if (input.val() != '') {
                                    segmentValue = input.val();
                                }
                            }
                        }
                        segmentArray.push(segmentValue);
                    });
                    messageLineArray.push(messageId);
                    messageLineArray.push(segmentArray);
                    messageArray.push(messageLineArray);
                });
                return JSON.stringify(messageArray);
            };

            form.verify({
                name: function(value){
                    if(value.length < 1){
                        return '请填写组名称';
                    }
                }
            });

            //监听提交
            form.on('submit(formSubmit)', function(data){
                var messageJson = buildMessageJson();
                layer.msg('提交中', {
                    shadeClose: false
                    ,icon: 16
                    ,shade: 0.01
                });
                var post = {
                    id: data.field.id,
                    name: data.field.name,
                    status: data.field.status,
                    json: messageJson
                };
//            console.log(post);
                $.ajax({
                    type: "POST",
                    url: "/message/saveGroupEnhance",
                    data: post,
                    success:function(response){
                        var dataObj=$.parseJSON(response);
                        if (dataObj.code===0) {
                            layer.msg('提交成功', {icon: 6});
                            var targetUrl = '/message/groupIndex';
//                        var groupId = (dataObj.groupId ? dataObj.groupId : '');
//                        if (groupId > 0) {
//                            targetUrl = '/message/editGroupEnhance/'+groupId;
//                        }
                            setTimeout(function(){
                                location.href = targetUrl;
                            }, 1000);
                        } else {
                            layer.msg(dataObj.msg, {icon: 5});
                        }
                    },
                    error: function (request, status, error) {
                        layer.msg('哦噢，网络开小差了', {icon: 5});
                    }
                });
                return false;
            });


            element.init();
            form.render();

            preview = function () {
                var board_html = '';
                var getTpl = tpl_preview.innerHTML;
                var data = {};
                laytpl(getTpl).render(data, function (html) {
                    board_html = html;
                });
                layer.open({
                    type: 1,
                    title: false,
                    area: ['700px', '450px'],
                    shadeClose: false,
                    content: board_html,
                    success: function(layero, index){
                        getCustomerSources();
                    }
                });
            };

            getCustomerSources = function () {
                $.ajax({
                    type: "GET",
                    url: "/customer_source/list_data/?page=1&limit=10&status=1",
                    success:function(response){
                        var dataObj=$.parseJSON(response);
                        if (dataObj.code === 0) {
                            var customerSources = dataObj.data;
                            displayCustomerSources(customerSources);
                        } else {
//                        layer.msg(dataObj.msg, {icon: 5});
                        }
                    },
                    error: function (request, status, error) {
                        layer.msg('哦噢，网络开小差了', {icon: 5});
                    }
                });
            };

            var displayCustomerSources = function(customerSources) {
                var html = '没有可用数据，请先上传数据再预览';
                if (customerSources.length > 0) {
                    html = '<select id="customerSourceId" lay-filter="selectedSource">';
//                html += '<option value="0">请选择</option>';
                    for (var i = 0; i < customerSources.length; i++) {
                        var item = customerSources[i];
                        html += '<option value="' + item.id + '">' + item.name + '</option>';
                    }
                    html += '</select>';
                }
                $('#customerSources').html(html);
                element.init();
                form.render();
                previewData();
            };

            previewData = function () {
                var customerSourceId = $('#customerSourceId').find('option:selected').val();
                if (customerSourceId <= 0) {
                    layer.msg('请选择数据', {icon: 5});
                    return false;
                }
                var messageJson = buildMessageJson();
                var msgIndex = layer.msg('正在生成预览...', {
                    shadeClose: false
                    ,icon: 16
                    ,shade: 0.01
                });
                var post = {
                    customerSourceId: customerSourceId,
                    json: messageJson
                };
//            console.log(post);
                $.ajax({
                    type: "POST",
                    url: "/message/previewData",
                    data: post,
                    success:function(response){
                        layer.close(msgIndex);
                        var dataObj=$.parseJSON(response);
                        if (dataObj.code===0) {
                            var messagePreviewData = dataObj.data;
                            displayMessagePreview(messagePreviewData);
                        } else {
                            layer.msg(dataObj.msg, {icon: 5});
                        }
                    },
                    error: function (request, status, error) {
                        layer.msg('哦噢，网络开小差了', {icon: 5});
                    }
                });
                return false;
            };

            var displayMessagePreview = function (messagePreviewData) {
                var board_html = '';
                var getTpl = tpl_preview_message.innerHTML;
                var data = {'messagePreviewData':messagePreviewData};
                laytpl(getTpl).render(data, function(html){
                    board_html = $.trim(html);
                });
                $('#messagePreview').html(board_html);
            };

            form.on('select(selectedSource)', function(data){
                previewData();
//            console.log(data.elem); //得到select原始DOM对象
//            console.log(data.value); //得到被选中的值
//            console.log(data.othis); //得到美化后的DOM对象
            });
        });
    </script>

    <script id="tpl_preview" type="text/html">
        <div class="layui-card">
            <div class="layui-card-header">验证消息预览</div>
            <div class="layui-card-body">
                <form class="layui-form" action="">
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择数据</label>
                        <div class="layui-input-inline" id="customerSources">
                        </div>
                    </div>
                </form>
                <hr class="layui-bg-gray">
                <div class="layui-row" id="messagePreview">

                </div>
            </div>
        </div>
    </script>
    <script id="tpl_preview_message" type="text/html">
        {{#  if(d.messagePreviewData.length>0){ }}
        {{#  layui.each(d.messagePreviewData, function(index, message){ }}
        <div class="layui-row">
            <div class="layui-form-item">
                <label class="layui-form-label">验证消息{{ index+1 }}</label>
            </div>
            <div class="layui-block">
                {{#  layui.each(message, function(index, item){ }}
                <hr class="layui-bg-gray">
                <div class="layui-inline">
                    {{ item[0] }}<span style="color: #CC0000">{{ item[1] }}</span>&nbsp;
                    {{#  if(item[3]>0){ }}
                    <span style="color: #0000FF">（还可填入 {{ item[3]*2 }} 个字符）</span>
                    {{#  } else if(item[3]<0) { }}
                    <span style="color: #CC0000">（超出 {{ item[3]*(-2) }} 个字符）</span>
                    {{#  } }}
                </div>
                {{#  }); }}
            </div>
        </div>
        <hr class="layui-bg-green">
        {{#  }); }}
        {{#  } else { }}
        <div class="layui-row">
            <span>数据为空，请重新选择</span>
        </div>
        {{#  } }}
    </script>
</div>
</body>
</html>
